<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\api;

use app\common\controller\ApiController;
use think\App;
use app\mill\model\Give as GiveModel;
use app\mill\model\App as AppModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Address as AddressModel;
use app\mill\model\Finance as FinanceModel;
use app\admin\model\Config as ConfigModel;
use app\mill\model\Db2 as Db2Model;
use think\Db;

/**
 * 用户公开控制器
 * @package app\user\admin
 */
class Index extends ApiController
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);

        $this->is_member();
    }
    //初始化
    protected function initialize(){
        parent::initialize();
        GiveModel::init();
    }
    //监听
    public function timer(){

        success('');
    }
    //菜单配置
    public function getMenu(){

        $menu = AppModel::getMenu(0,$this->member);

        success('', array('list' => $menu));
    }
    //产品详情
    public function detail(){
        // 获取参数
        $data = input('');

        $where[] = ['give_sn','=',$data['give_sn']];

        $give = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("a.*,o.batch,g.status as give_status,g.give_sn,g.archives_sn,g.counter,concat(g.counter,'/',a.number) as number_str")
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($where)
            ->find();

        if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
        $give['status_str'] = GiveModel::$give_status[$give['give_status']];

        success('操作成功',$give);
    }
    //扫码更新产品进度
    public function ableGive()
    {

        $role = GiveModel::$role;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $_log_time = time();
            $_log_i = 0;
            //file_put_contents('扫码.log',date('Y-m-d H:i:s',$_log_time)."  记数：{$_log_i}\r\n".json_encode($data,JSON_UNESCAPED_UNICODE)."\r\n\r\n",FILE_APPEND);

            //获取离线状态下的用户ID
            $archives_sn = !empty($data['archives_sn'])?$data['archives_sn']:'';
            $give_sn = explode(',',$data['give_sn']);
            $user_ids = !empty($data['uid'])?explode(',',$data['uid']):'';
            $staff_ids = !empty($data['staff_id'])?explode(',',$data['staff_id']):'';
            $car_ids = !empty($data['car_id'])?explode(',',$data['car_id']):'';
            $color_s = !empty($data['color'])?explode(',',$data['color']):'';
            $address_sn_s = !empty($data['address_sn'])?explode(',',$data['address_sn']):'';

            $user = $this->member;

            $data_list = [];
            if(!empty($give_sn)){
                $_log_str = '';
                foreach ($give_sn as $k=>$v){

                    $uid = !empty($user_ids[$k])?$user_ids[$k]:$user['id'];
                    $staff_id = !empty($staff_ids[$k])?$staff_ids[$k]:$user['uid'];
                    $car_id = !empty($car_ids[$k])?$car_ids[$k]:$car_ids;
                    $color = !empty($color_s[$k])?$color_s[$k]:$color_s;
                    $address_sn = !empty($address_sn_s[$k])?$address_sn_s[$k]:$address_sn_s;
                    $user = Db::name('admin_user')
                        ->alias('u')
                        ->field('u.*,u.id as uid,g.name as group_name,g.app_page,g.give_sort')
                        ->leftJoin('admin_user_group g','g.id=u.group')
                        ->where(['u.id'=>$uid])
                        ->find();
                    if(!empty($staff_id)){
                        $user['nickname'] = Db::name('mill_staff')->where(['id'=>$staff_id])->value('staff');
                        $user['uid'] = $staff_id;
                    }

                    $where = [
                        ['g.give_sn','=',$v],
                    ];

                    //判断产品编号是否完整
                    if(strpos($v,'-') === false){

                        //匹配批次
                        if(!empty($archives_sn)){
                            $where = [
                                ['g.give_sn','like',"%-{$v}"],
                                ['g.archives_sn','=',$archives_sn],
                            ];
                        }
                        else {
                            $where = '1=2';
                            $msg = '该产品不存在';
                        }
                    }

                    $give = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->field('g.*,g.status as give_status,a.one_area,a.number as archives_number,c.is_lock,o.client_id,o.status as order_status,o.is_lock as is_lock2,o.give_sort')
                        ->leftJoin('mill_order o','o.id=g.order_id')
                        ->leftJoin('mill_client c','c.id=o.client_id')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->where($where)
                        ->find();

                    if($give && $give['order_status'] > 0){

                        // 验证权限
                        $msg = GiveModel::role($user,$give['status'],$give['give_sort']);
                        //验证该产品是否已冻结
                        if($give['is_lock'] == 0 || $give['is_lock2'] == 0)$msg = '该工程已冻结，请联系管理员';
                        //验证该产品是否已取消生产
                        if($give['quality_status'] == -3)$msg = '该产品已取消生产';
                        //验证该产品是否已取消生产工艺
                        if(empty($give['give_sort']))$msg = '该工程未选择生产工艺';
                        //匹配批次
                        if(empty($msg) && $archives_sn && !in_array($give['archives_sn'],explode(',',$archives_sn)))$msg = '批次不匹配';
                        //匹配焊接颜色
                        if(empty($msg) && $color){
                            $give_color = Db::name('mill_order_archives')->where(['id'=>$give['archives_id']])->value('color');
                            if($color != $give_color)$msg = '颜色不匹配';
                        }
                        //选择车辆
                        if($user['app_page'] == 'address' && empty($car_id))$msg = '请选择车辆';

                        if(empty($msg)){
                            //发货状态，绑定车牌ID
                            if($user['app_page'] == 'address'){
                                //如果发货单号为空，则获取最近一个发货单号
                                $address_sn = trim($address_sn);
                                if(empty($address_sn))$address_sn = AddressModel::lastAddressSn($uid,$give);
                                $give['is_address'] = 1;
                                $give['car_id'] = $car_id;
                                $give['address_sn'] = $address_sn;
                            }
                            //------------补扫情况，自动补满之前所有状态-------------
                            $sup_status = $user['give_sort'];//需要补充到的状态
                            $save = GiveModel::giveToStatus($user,$sup_status,$give);
                            $log_list = isset($save['log_list'])?$save['log_list']:'';

                            $give['status'] = $save['status'];

                            unset($save['log_list']);
                            //----------补扫情况，自动补满之前所有状态 END----------

                            $give_where = ['id'=>$give['id']];
                            if(Db::name('mill_order_archives_give')->where($give_where)->update($save)){
                                //生成扫码记录
                                GiveModel::addGiveLog($log_list);
                                //检查更新产品主体状态
                                ArchivesModel::checkStatus($give,$give['give_sort']);

                                //TODO 同步更新至旧数据库
                                //同步更新旧数据库的扫码产品进度，仅限喷涂
                                if(!empty($color))Db2Model::giveEdit($give);
                            }

                            $give = Db::name('mill_order_archives_give')
                                ->alias('g')
                                ->field("a.*,g.id as id,o.batch,o.engineering,g.status as give_status,g.give_sn,g.archives_sn,g.counter,concat(g.counter,'/',a.number) as number_str")
                                ->leftJoin('mill_order o','o.id=g.order_id')
                                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                                ->where(['g.id'=>$give['id']])
                                ->find();
                        }

                    }
                    else{
                        if(empty($msg))$msg = '该产品不存在';
                        $give['give_sn'] = $v;

                    }

                    if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
                    //1：成功 0：失败
                    $give['address_sn'] = empty($address_sn)?'':$address_sn;
                    $give['status_code'] = empty($msg)?1:0;
                    $give['nickname'] = $user['nickname'];
                    $give['group_name'] = $user['group_name'];
                    //提示状态
                    $give['code_str'] = '该产品不存在';
                    if(isset($give['give_status']))$give['code_str'] = GiveModel::$give_status[$give['give_status']];

                    $give['status_str'] = $msg?$msg:'已上传';

                    $give['time_str'] = date('Y.m.d H:i');

                    $data_list[] = $give;

                    $_log_str .= "产品编号：{$give['give_sn']}  状态：{$give['status_str']}";
                }

                //file_put_contents('扫码reust.log',date('Y-m-d H:i:s',$_log_time)."  记数：{$_log_i}\r\n".$_log_str."\r\n\r\n",FILE_APPEND);

                success('操作成功',$data_list);
            }
            errors('操作失败');
        }

        errors('操作异常');
    }
    //分配发货单号
    public function addressSn(){

        success('操作成功',['address_sn'=>GiveModel::getAddressSn()]);
    }
    //确认发货
    public function carGive()
    {

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            if (!isset($data['address_sn']))$data['address_sn'] = '';
            if (!isset($data['give_sn']))$data['give_sn'] = '';
            if (!isset($data['car_id']))$data['car_id'] = '';

            $address_sn_s = unique($data['address_sn']);

            //按批次分组
            $where = [
                ['address_sn','in',$address_sn_s],
                ['address_status','=',0],

            ];
            $archives_ids = '';
            $give_list = Db::name('mill_order_archives_give')
                ->field('address_sn,order_id,archives_sn,GROUP_CONCAT(id) as give_ids,GROUP_CONCAT(DISTINCT archives_id) as archives_ids')
                ->where($where)
                ->group('address_sn,order_id')
                ->select();

            $user = $this->member;

            $data_list = [];
            if(!empty($give_list)){

                $time = time();

                foreach ($give_list as $v){

                    $archives_ids .= ",{$v['archives_ids']}";
                    //分配发货单号
                    if(strpos($address_sn_s,$v['address_sn']) !== false){
                        $address_sn = $v['address_sn'];
                        $address_sn_s = str_replace($v['address_sn'],"",$address_sn_s);
                    }
                    else $address_sn = GiveModel::getAddressSn($time);

                    if(!empty($v['give_ids'])){
                        $msg = '';

                        $save = [
                            'address_status'        =>  1,
                            'address_date'          =>  date('Y-m-d',$time),
                            'address_time'          =>  $time,
                            'address_sn'            =>  $address_sn,
                        ];

                        $give_where = [['id','in',$v['give_ids']]];

                        Db::name('mill_order_archives_give')->where($give_where)->update($save);
                        Db::name('mill_order_archives_give_log')->where([['give_id','in',$v['give_ids']]])->update($save);

                        //更新发货金额
                        FinanceModel::updateAddressPrice($v['order_id'],$address_sn);

                    }
                    else $msg = '该产品已确认发货';

                    //1：成功 0：失败
                    $give['status_code'] = empty($msg)?1:0;
                    $give['nickname'] = $user['nickname'];
                    $give['group_name'] = $user['group_name'];
                    //提示状态
                    $give['code_str'] = '';
                    $give['status_str'] = $msg?$msg:'已上传';
                    $give['time_str'] = date('Y.m.d H:i');

                    $data_list[] = $give;
                }

                success('操作成功',[]);
            }
            success('后台已确认装车',[]);
        }

        errors('操作异常');
    }
    //扫码质检产品状态
    public function qualityErrors(){

        $config = new ConfigModel();

        $mill_quality_errors = $config->getConfig('mill_quality_errors');
        $mill_quality_errors = explode("\r\n",$mill_quality_errors);

        $list = [];
        foreach ($mill_quality_errors as $k=>$v){
            $list[] = [
                'title'     =>  $v,
            ];
        }

        success('', array('list' => $list, 'pagesize' => 999, 'total' => 999, 'pindex' => 999, 'total_pages' => 1));
    }
    //扫码质检产品环节
    public function qualityGiveStatus(){

        $give_status = GiveModel::$give_status_search;
        unset($give_status[0]);

        $list = [];
        foreach ($give_status as $k=>$v){
            $list[] = [
                'id'        =>  $k,
                'title'     =>  "{$v}环节",
            ];
        }

        success('', array('list' => $list, 'pagesize' => 999, 'total' => 999, 'pindex' => 999, 'total_pages' => 1));
    }
    //扫码质检产品
    public function quality(){
        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            //获取离线状态下的用户ID
            $give_sn = explode(',',$data['give_sn']);
            $user_ids = !empty($data['uid'])?explode(',',$data['uid']):'';
            $staff_ids = !empty($data['staff_id'])?explode(',',$data['staff_id']):'';
            $quality_errors_s = !empty($data['quality_errors'])?$data['quality_errors']:'';
            $quality_note_s = !empty($data['quality_note'])?$data['quality_note']:'';
            $give_status_s = !empty($data['give_status'])?$data['give_status']:'';

            $user = $this->member;

            $data_list = [];
            if(!empty($give_sn)){
                foreach ($give_sn as $k=>$v){

                    $uid = !empty($user_ids[$k])?$user_ids[$k]:$user['id'];
                    $staff_id = !empty($staff_ids[$k])?$staff_ids[$k]:$user['uid'];
                    $quality_errors = !empty($quality_errors_s[$k])?$quality_errors_s[$k]:$quality_errors_s;
                    $quality_note = !empty($quality_note_s[$k])?$quality_note_s[$k]:$quality_note_s;
                    $give_status = !empty($give_status_s[$k])?$give_status_s[$k]:$give_status_s;
                    $user = Db::name('admin_user')
                        ->alias('u')
                        ->field('u.*,u.id as uid,g.name as group_name,g.app_page,g.give_sort')
                        ->leftJoin('admin_user_group g','g.id=u.group')
                        ->where(['u.id'=>$uid])
                        ->find();
                    if(!empty($staff_id)){
                        $user['nickname'] = Db::name('mill_staff')->where(['id'=>$staff_id])->value('staff');
                        $user['uid'] = $staff_id;
                    }

                    $where = [['g.give_sn','=',$v]];

                    $give = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->field('g.*,g.status as give_status,a.one_area,a.number as archives_number,c.is_lock,o.client_id,o.status as order_status,o.is_lock as is_lock2,o.give_sort')
                        ->leftJoin('mill_order o','o.id=g.order_id')
                        ->leftJoin('mill_client c','c.id=o.client_id')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->where($where)
                        ->find();

                    if($give && $give['order_status'] > 0){

                        //验证该产品是否已冻结
                        if($give['is_lock'] == 0 || $give['is_lock2'] == 0)$msg = '该工程已冻结，请联系管理员';
                        if(empty($quality_errors))$msg = '请选择错误原因';
                        if(empty($give_status))$msg = '请选择责任环节';

                        $give_log = Db::name('mill_order_archives_give_log')->alias('g')->where($where)->where(['g.status'=>$give_status])->find();
                        if(empty($give_log))$msg = '该责任环节暂无扫描记录';

                        if(empty($msg)){

                            $post = [
                                'give_sn'               =>  $v,
                                'quality_note'          =>  $quality_note,
                                'quality_errors'        =>  $quality_errors,
                                'give_status'           =>  $give_status,
                            ];
                            //质检
                            GiveModel::quality($user,$post);

                            $give = Db::name('mill_order_archives_give_quality')
                                ->alias('q')
                                ->field("q.*,o.batch,o.engineering,g.counter,q.quality_errors,q.status as give_status,concat(g.counter,'/',a.number) as number_str")
                                ->leftJoin('mill_order o','o.id=q.order_id')
                                ->leftJoin('mill_order_archives a','a.id=q.archives_id')
                                ->leftJoin('mill_order_archives_give g','g.id=q.give_id')
                                ->where(['q.give_sn'=>$data['give_sn']])
                                ->find();

                        }

                    }
                    else{
                        if(empty($msg))$msg = '该产品不存在';
                        $give['give_sn'] = $v;

                    }

                    $give['nickname'] = $user['nickname'];
                    $give['group_name'] = $user['group_name'];

                    //提示状态
                    $give['code_str'] = GiveModel::$give_status[abs($give['give_status'])];
                    if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
                    $give['status_code'] = 1;
                    $give['status_str'] = '已上传';
                    $give['time_str'] = date('Y.m.d H:i');

                    $data_list[] = $give;
                }

                success('操作成功',$data_list);
            }

        }

        errors('操作异常');
    }
    //人员列表
    public function staffList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $where = ['status'=>1,'type'=>3];
        $order = 'id desc';

        $list = Db::name('mill_staff')
            ->field('id,staff as name')
            ->where($where)
            ->order($order)
            ->select();

        $total = Db::name('mill_staff')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    //车牌列表
    public function carList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $role_status = GiveModel::$role[$user['group']];

        $where = ['status'=>1];
        $order = 'id desc';

        $list = Db::name('mill_car')
            ->where($where)
            ->order($order)
            //->limit((($pindex-1)*$psize),$psize)
            ->select();

        $total = Db::name('mill_car')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
        //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    //批次列表
    public function batchList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        //发货状态
        $status = GiveModel::$last_give_status;

        $archives_sn = input('archives_sn');
        $archives_sn = str_replace('，',',',strtoupper($archives_sn));
        $archives_sn_arr = explode(',',$archives_sn);
        $where_sn = '';
        if(!empty($archives_sn_arr) && !empty($archives_sn)){
            foreach ($archives_sn_arr as $sn){
                if(!empty($where_sn))$where_sn .= ' OR ';
                $where_sn .= " o.archives_sn like '%{$sn}%'";
            }
        }

        $where = [['o.status','=',1],['g.status','<',$status]];
        $order = 'o.status_time desc,o.id desc';

        $list = Db::name('mill_order')
            ->field("o.id,o.archives_sn,o.batch,concat(o.archives_sn,'/',o.batch) as batch_str")
            ->alias('o')
            ->leftJoin('mill_order_archives_give g','g.order_id=o.id')
            ->where($where)
            ->where($where_sn)
            ->group('o.id')
            ->order($order)
            ->select();

        $total = Db::name('mill_order')
            ->alias('o')
            ->leftJoin('mill_order_archives_give g','g.order_id=o.id')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    //颜色列表
    public function colorList(){
        $user = $this->member;

        $archives_sn = input('archives_sn');
        if(empty($archives_sn))errors('请选择批次');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $where = [['archives_sn','in',$archives_sn]];
        $order = 'id asc';

        $list = Db::name('mill_order_archives')
            ->field("distinct color")
            ->where($where)
            ->order($order)
            ->select();

        $total = Db::name('mill_order')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    //批次发货情况统计
    public function carBatchStat(){
        $user = $this->member;

        $archives_sn = input('archives_sn');
        $color = input('color');
        $car_id = input('car_id');
        $address_sn = input('address_sn');
        if(empty($archives_sn))errors('请选择批次');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $status = $user['give_sort'];

        $archives_sn_arr = explode(',',$archives_sn);
        $list = [];
        foreach ($archives_sn_arr as $sn){

            $order = Db::name('mill_order')->where([['archives_sn','=',$sn]])->find();

            $stat['engineering'] = $order['engineering'];
            $stat['archives_sn'] = $order['archives_sn'];
            $stat['batch'] = $order['batch'];
            $stat['color'] = $color;
            //总数量
            $stat_where = [['g.order_id','=',$order['id']]];
            if($color)$stat_where[] = ['a.color','=',$color];
            $stat['give_sum'] = Db::name('mill_order_archives_give')
                ->alias('g')
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->where($stat_where)
                ->count('g.id');

            $status_str = GiveModel::$give_status[$status];
            //已扫码数量
            $stat_where = [
                ['g.order_id','=',$order['id']],
                ['g.status','=',$status]
            ];
            //焊接
            if($color){
                //已焊接数量
                $stat_where[] = ['a.color','=',$color];
                $stat['ok_sum'] = Db::name('mill_order_archives_give_log')
                    ->alias('g')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($stat_where)
                    ->count();
            }
            //开料，折弯，发货
            else $stat['ok_sum'] = Db::name('mill_order_archives_give_log')->alias('g')->where($stat_where)->count();

            $stat['status_str'] = "总数:{$stat['give_sum']}/已{$status_str}:{$stat['ok_sum']}/未{$status_str}:".($stat['give_sum']-$stat['ok_sum']);

            //扫码人情况
            if($user['app_page'] == 'address'){
                $stat_where[] = ['g.status_uid','=',$user['uid']];
                if($car_id)$stat_where[] = ['g.car_id','=',$car_id];
                if($address_sn)$stat_where[] = ['g.address_sn','=',$address_sn];

                $stat['user_ok_sum'] = Db::name('mill_order_archives_give_log')->alias('g')->where($stat_where)->count();

                $stat['status_str'] = "当车已扫:{$stat['user_ok_sum']}/未{$status_str}:".($stat['give_sum']-$stat['ok_sum']);
            }

            $list[] = $stat;
        }

        $total = count($archives_sn_arr);

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    //新增车牌号
    public function addCar(){

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            $rule = [
                'plate_number|车牌号' => 'require',
            ];
            if(($message =$this->validate($data,$rule)) !== true)errors([],$message);

            //函数:SBC_DBC  中文标点转英文标点
            //函数:replaceSpecialChar  去除所有标点字符包括空格
            //函数:strtoupper  转大写
            $data['plate_number'] = filterStr($data['plate_number']);
            $update = [
                'plate_number'  =>  $data['plate_number'],
            ];
            $count = Db::name('mill_car')->where($update)->count();
            if($count > 0)errors('该车牌号已存在');
            $re = Db::name('mill_car')->insert($update);

            if(!empty($re))success('提交成功');
            errors('提交失败,请重试');

        }

    }
}
